/**
 * 发票袋设置
 */
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Popconfirm, Popover, Badge, message, Radio } from 'antd'
import { messages } from "share/common"
import constants from 'share/constants'
import errorMessage from 'share/errorMessage'
import InvoiceBagSettingDetail from './slide-frame-detail'
import TableList from '../table-list'
import requestAndExpenseService from '../request-and-expense-settings.service'
import {batchOperations} from "components/template/wrapped-table-params/batch-operations";

const RadioGroup = Radio.Group;

class InvoiceBagSetting extends Component {

  state = {
    loading: false,
    slideFrameInfo: {
      title: messages('expense-15.key109')/*发票袋设置*/,
      content: InvoiceBagSettingDetail,
      params: { defaultLabel: [] }
    }
  };

  componentDidMount() {
    this.getDefaultTag();
  }

  getDefaultTag = () => {
    let { slideFrameInfo } = this.state;
    requestAndExpenseService.getTagDetail('READY_TO_MAIL').then(res => {
      let row = res.data && res.data.rows && res.data.rows[0];
      slideFrameInfo.params = { defaultLabel: row ? [{ id: row.id, name: row.name }] : [] };
      this.setState({ slideFrameInfo });
    })
  };

  searchForm = [{
    id: 'levelCodes',
    dataIndex: 'levelCode',
    label: messages('expense-15.key110')/*层级*/,
    component: (
      <RadioGroup>
        <Radio value="COMPANY">{messages('expense-15.key111')/*公司*/}</Radio>
        <Radio value="TENANT">{messages('expense-15.key112')/*租户*/}</Radio>
      </RadioGroup>
    ),
    tagParser: value => {
      return value === "COMPANY" ? messages('expense-15.key111')/*公司*/ : messages('expense-15.key112')/*租户*/;
    }
  }, {
    id: 'distLevelOrgIds',
    dataIndex: 'distLevelOrgName',
    label: messages('expense-15.key113')/*启用公司*/,
    component: 'Chooser',
    props: {
      labelKey: 'name',
      valueKey: 'id',
      type: 'priority_company'
    },
    parser: value => ({
      distLevelOrgIds: value ? value.map(item => item.id) : null
    })
  }];

  columns = [{
    title: messages('expense-15.key110')/*层级*/,
    dataIndex: 'levelCode',
    render: value => value === 'COMPANY' ? messages('expense-15.key111')/*公司*/ : messages('expense-15.key112')/*租户*/
  }, {
    title: messages('expense-15.key114')/*所属组织*/,
    dataIndex: 'levelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('expense-15.key113')/*启用公司*/,
    dataIndex: 'distLevelOrgName',
    render: value => <Popover content={value} placement="topLeft">{value}</Popover>
  }, {
    title: messages('expense-15.key115')/*首位限制*/,
    dataIndex: 'preFix'
  }, {
    title: messages('expense-15.key116')/*位数限制*/,
    dataIndex: 'maxLength'
  }, {
    title: messages('expense-15.key117')/*关联报销单数量*/,
    dataIndex: 'range',
    render: (value, record) => (
      <Popover content={`${record.minExpenseReportSize} ～ ${record.maxExpenseReportSize}`}>
        {record.minExpenseReportSize} ～ {record.maxExpenseReportSize}
      </Popover>
    )
  }, {
    title: messages('expense-15.key118')/*关联报销单状态*/,
    dataIndex: 'statuses',
    render: value => {
      if (value && value.length) {
        let showValue = [];
        value.map(key => {
          constants.expenseStatus.map(item => {
            String(item.value) === String(key) && showValue.push(item.label)
          });
        });
        return <Popover placement="topLeft" content={showValue.join('、')}>{showValue.join('、')}</Popover>
      } else {
        return '-'
      }
    }
  }, {
    title: messages('expense-15.key119')/*报销单标签*/,
    dataIndex: 'labels',
    render: value => {
      if (value && value.length) {
        let showValue = [];
        value.map(item => showValue.push(item.name));
        return <Popover placement="topLeft" content={showValue.join('、')}>{showValue.join('、')}</Popover>
      } else {
        return '-'
      }
    }
  }, {
    title: messages('common.column.status')/*状态*/,
    dataIndex: 'enabled',
    render: value => (
      <Badge
        status={value ? 'success' : 'error'}
        text={value ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
      />
    )
  }
  // , {
  //   title: messages('common.operation')/*操作*/,
  //   dataIndex: 'id',
  //   render: (value, record) => (
  //     record.readOnly ? (
  //       <span onClick={e => e.stopPropagation()} className="font-disabled">{messages('common.delete')/*删除*/}</span>
  //     ) : (
  //       <Popconfirm
  //         title={messages('common.confirm.delete')/*确定要删除吗？*/}
  //         onConfirm={() => this.handleDelete(value)}
  //       >
  //         <a onClick={e => e.stopPropagation()}>{messages('common.delete')/*删除*/}</a>
  //       </Popconfirm>
  //     )
  //   )
  // }
  ];

  service = (page, size, searchParams) => {
    let params = {};
    searchParams.levelCodes && (params.levelCodes = [searchParams.levelCodes]);
    searchParams.distLevelOrgIds && (params.distLevelOrgIds = searchParams.distLevelOrgIds);
    return requestAndExpenseService.getBagSettingList(page, size, params);
  };

  handleDelete = id => {
    this.setState({ loading: true });
    requestAndExpenseService.deleteBag(id).then(() => {
      this.setState({ loading: false });
      this.advancedTableRef.getList();
      message.success(messages('common.delete.success',{arg1: ''})/*{arg1} 删除成功*/);
    }).catch(e => {
      this.setState({ loading: false });
      errorMessage(e.response);
    })
  };

  render() {
    const { loading, slideFrameInfo } = this.state;
    let tableParams =  batchOperations({
      rowKey: 'id'
    }, [
    //   {
    //   type: 'DELETE',
    //   service: requestAndExpenseService.batchDeleteInvoiceBag,
    //   onOk: () => this.advancedTableRef.getList()
    // },
      {
      type: 'ENABLE',
      service: requestAndExpenseService.batchOpenOrCloseInvoiceBag,
      onOk: () => this.advancedTableRef.getList()
    }, {
      type: 'DISABLE',
      service: requestAndExpenseService.batchOpenOrCloseInvoiceBag,
      onOk: () => this.advancedTableRef.getList()
    }], this);
    return (
      <div className="full-height-page" style={{ marginTop: -16, height: 'calc(100vh - 50px)' }}>
        <TableList
          slideFrameInfo={slideFrameInfo}
          afterClose={refresh => typeof refresh === 'boolean' && refresh && this.advancedTableRef.getList()}
          tableParams={{
            tableName: 'invoice-bag-setting-table',
            loading,
            rowKey: 'id',
            searchForm: this.searchForm,
            columns: this.columns,
            service: this.service,
            onRef: ref => this.advancedTableRef = ref,
            ...tableParams
          }}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return { }
}

export default connect(mapStateToProps)(InvoiceBagSetting)
